package com.xiaoshuai.controller;

import com.alibaba.excel.EasyExcel;
import com.xiaoshuai.po.User;
import com.xiaoshuai.service.UseService;
import com.xiaoshuai.userListener.UserListener;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.net.URLEncoder;

@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private UseService useService;

    @PostMapping("/upload")
    @ResponseBody
    public void upload(MultipartFile file, HttpServletResponse response) throws IOException {
        long t1 = System.currentTimeMillis();
        EasyExcel.read(file.getInputStream(), User.class, new UserListener(useService)).sheet().doRead();
        long t2 = System.currentTimeMillis();
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().print("导入数据成功，共用时：" + (t2 - t1)+"毫秒");
    }
    @GetMapping("/download")
    public void download(HttpServletResponse response) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("资产列表", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), User.class).sheet("模板").doWrite(useService.getData());
    }
}
